package com.example.servlet;

import com.example.dao.AnswerDAO;
import com.example.dao.QuestionDAO;
import com.example.model.Answer;
import com.example.model.Question;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/viewPost")
public class ViewPostServlet extends HttpServlet {
    private QuestionDAO questionDAO;
    private AnswerDAO answerDAO;

    @Override
    public void init() throws ServletException {
        try {
            questionDAO = new QuestionDAO();
            answerDAO = new AnswerDAO();
        } catch (Exception e) {
            throw new ServletException("初始化 DAO 失败", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String postIdParam = request.getParameter("id");
        if (postIdParam == null || postIdParam.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少帖子 ID 参数");
            return;
        }

        int postId;
        try {
            postId = Integer.parseInt(postIdParam);
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "帖子 ID 格式错误");
            return;
        }

        try {
            // 获取帖子信息
            Question post = questionDAO.getQuestionById(postId);
            if (post == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "帖子未找到");
                return;
            }

            // 更新浏览次数
            questionDAO.incrementViewCount(postId);
            
            // 重新获取帖子信息以获取更新后的浏览次数
            post = questionDAO.getQuestionById(postId);

            // 获取回复列表
            List<Answer> answers = answerDAO.getAnswersByQuestionId(postId);

            // 将数据传递到 JSP 页面
            request.setAttribute("post", post);
            request.setAttribute("answers", answers);
            request.getRequestDispatcher("viewPost.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误: " + e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }
}